package com.g4.shoppingback.controller;


import com.g4.shoppingback.annotation.WriteLog;
import com.g4.shoppingback.common.PageVo;
import com.g4.shoppingback.common.Result;
import com.g4.shoppingback.pojo.DdUsersInfo;
import com.g4.shoppingback.pojo.Role;
import com.g4.shoppingback.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2022-02-19
 */
@RestController
@CrossOrigin
@RequestMapping("/shoppingback/role")
public class RoleController {

    @Autowired
    private IRoleService iRoleService;

    /**
     * 根据id查询角色
     * @param id 角色id
     * @return 单个角色信息
     */
    @GetMapping("/{id}")
    public Result selectRoleById(@PathVariable Integer id){
        Role role = iRoleService.selectRoleById(id);
        return Result.ok(role);
    }

    /**
     * 根据分页信息或角色名查询角色
     * @param pageVo 封装了查询关键字和页数
     * @return 返回分页信息
     */
    @PreAuthorize("hasAnyAuthority('miShop:role:find')")
    @GetMapping
    public Result selectRoleByPage(PageVo pageVo){
        PageVo pageResult = iRoleService.selectRoleByPage(pageVo);
        return Result.ok(pageResult);
    }

    /**
     * 根据角色id删除角色
     * @param id 角色id
     * @return 返回提示
     */
    @WriteLog("删除角色")
    @PreAuthorize("hasAnyAuthority('miShop:role:delete')")
    @DeleteMapping("/{id}")
    public Result deleteRoleById(@PathVariable Integer id){
        int row = iRoleService.deleteRoleById(id);
        if(row==1){
            return Result.success("删除成功!");
        }
        if(row==2){
            return Result.error("该角色已被用户使用,不能删除!");
        }
        return Result.error("删除失败");

    }

    /**
     * 查询所有角色
     * @return 多个角色
     */
    @GetMapping("/selectRoles")
    public Result selectRoles(){
        List<Role> roles = iRoleService.selectRoles();
        if(roles!=null)return Result.ok(roles);
        return Result.error("该用户未分配角色!");
    }

    /**
     * 新增角色
     * @param role 传入角色对象
     * @return 返回提示
     */
    @WriteLog("新增角色")
    @PreAuthorize("hasAnyAuthority('miShop:role:add')")
    @PostMapping
    public Result addRole(@RequestBody Role role){
        int row = iRoleService.addRole(role);
        if(row==1){
            return Result.success("新增角色成功!");
        }else {
            return Result.error("新增角色失败!");
        }
    }

    /**
     * 修改角色
     * @param role 传入角色对象
     * @return 返回提示
     */
    @WriteLog("修改角色")
    @PreAuthorize("hasAnyAuthority('miShop:role:update')")
    @PutMapping
    public Result updateRole(@RequestBody Role role){
        int row = iRoleService.updateRole(role);
        if(row==1){
            return Result.success("修改角色成功!权限生效需要重新登录!");
        }else {
            return Result.error("修改角色失败!");
        }
    }


}
